package threadDemo12;

import java.util.concurrent.locks.ReentrantLock;

public class Ticket implements Runnable {
    // 票的数量
    private int ticket = 100;
    private Object obj = new Object();
    private ReentrantLock lock = new ReentrantLock(); // 创建锁对象

    @Override
    public void run() {
        while (true) {
            // 同步代码块：死锁
            // synchronized (obj){ // 多个线程必须使用同一把锁
            try {
                lock.lock();
                if (ticket <= 0) {
                    // 卖完了退出循环
                    break;
                } else {
                    Thread.sleep(50);
                    ticket--;
                    System.out.println(Thread.currentThread().getName() + "在买票，还剩下" + ticket + "张票");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
            // }
        }
    }

}
